﻿//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Windows;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Collections;
using System.Collections.Generic;

using P2.Cuberry.Framework.Helper;
using P2.Cuberry.Modules.Framework.ModuleManager.BusinessEntities;

namespace P2.Cuberry.Modules.Framework.ModuleManager
{
    /// <summary>
    /// Interaction logic for ModulesDetailsView.xaml
    /// </summary>
    public partial class ModulesDetailsView : Window, IModulesDetailsView
    {

        public ModulesDetailsView()
        {
            InitializeComponent();
        }

        public ModulesDetailsPresentationModel Model
        {
            get { return this.DataContext as ModulesDetailsPresentationModel; }
            set
            {                
                this.DataContext = value;
            }
        }

        #region Standard DetailView Functionalities
               
        public void CellFocusable(Object sender, RoutedEventArgs e)
        {
            try
            {
                System.Windows.Controls.DataGridRow dgrow = (System.Windows.Controls.DataGridRow)sender;
                DataGridCellsPresenter presenter = GeneralHelper.GetVisualChild<DataGridCellsPresenter>(dgrow);

                // try to get the cell but it may possibly be virtualized
                System.Windows.Controls.DataGridCell cell = (System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
                if (cell == null)
                {
                    // now try to bring into view and retreive the cell
                    ApplicationResourceList.ScrollIntoView(dgrow, ApplicationResourceList.Columns[0]);
                    cell = (System.Windows.Controls.DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(0);
                }

                cell.Focus();
                ((System.Windows.Controls.DataGridRow)sender).Loaded -= CellFocusable;
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }
        
        public BusinessEntities.XAppResources SelectedXAppResource
        {
            get
            {
                if (ApplicationResourceList.SelectedItem != null)
                {
                    return (BusinessEntities.XAppResources)ApplicationResourceList.SelectedItem;
                }
                else
                    return null;
            }
        }

        public BusinessEntities.XConfigValidationMandatoryFields SelectedConfigValidationMandatoryFields
        {
            get
            {
                if (ConfigValidationMandatoryFieldsList.SelectedItem != null)
                {
                    return (BusinessEntities.XConfigValidationMandatoryFields)ConfigValidationMandatoryFieldsList.SelectedItem;
                }
                else
                    return null;
            }
        }

        public BusinessEntities.XConfigLogFields SelectedFieldTracking
        {
            get
            {
                if (FieldTrackingList.SelectedItem != null)
                {
                    return (BusinessEntities.XConfigLogFields)FieldTrackingList.SelectedItem;
                }
                else
                    return null;
            }
        }

        public BusinessEntities.XConfigUIControls SelectedConfigUIContol 
        {
            get 
            { 
                if (ConfigUIControlsList.SelectedItem != null)
                    return (BusinessEntities.XConfigUIControls)ConfigUIControlsList.SelectedItem;
                else
                    return null;
            } 
        }

        public BusinessEntities.XConfigWorkflowUIControls SelectedConfigWorkflowUIControl 
        {
            get 
            {
                if (WorkflowUIControlsList.SelectedItem != null)
                    return WorkflowUIControlsList.SelectedItem as BusinessEntities.XConfigWorkflowUIControls;
                else
                    return null;
            } 
        }

        public BusinessEntities.XFieldValidation SelectedFieldValidation
        {
            get
            {
                if (FieldValidationsList.SelectedItem != null)
                    return FieldValidationsList.SelectedItem as BusinessEntities.XFieldValidation;
                else
                    return null;
            }
        }

        public void UpdateFocusedControl()
        {
            try
            {
                TextBox focusedTextBox = Keyboard.FocusedElement as TextBox;
                if (focusedTextBox == null)
                    return;
                
                BindingExpression textBindingExpr =
                  focusedTextBox.GetBindingExpression(TextBox.TextProperty);
                if (textBindingExpr == null)
                    return;

                textBindingExpr.UpdateSource();
            }
            catch (Exception)
            {
            }
        }

        private void ApplicationResourceList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ApplicationResourceList.SelectedItem != null)
            {
                BusinessEntities.XAppResources selectedItem = (BusinessEntities.XAppResources)ApplicationResourceList.SelectedItem;
                Model.EditAppResource (selectedItem);
            }
        }

        private void ConfigValidationMandatoryFieldsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ConfigValidationMandatoryFieldsList.SelectedItem != null)
            {
                BusinessEntities.XConfigValidationMandatoryFields selectedItem = (BusinessEntities.XConfigValidationMandatoryFields)ConfigValidationMandatoryFieldsList.SelectedItem;
                Model.EditConfigValidationMandatoryFields(selectedItem);
            }
        }

        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            UpdateFocusedControl();

            if (Model.Save())
            {
                this.DialogResult = true;
                this.Close();
            }

            //P2MessageStack messageStack = Model.Save();
            //StatusStrip.addStatusBlock(Model.MessageStack);            
        }

        private void CloseBtn_Click(object sender, RoutedEventArgs e)
        {
            bool result = AskSave();
            if (result) this.Close();
        }
                     
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            e.Cancel = !this.AskSave();
        }
        
        public bool AskSave()
        {
            UpdateFocusedControl();
            if (!Model.IsReadOnly && Model.ModelIsModified)
            
            {
                MessageBoxOptions opt = MessageBoxOptions.None;
                if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
                MessageBoxResult result = MessageBox.Show(P2Translator.GetResource("ModuleNotSaved"), P2Translator.GetResource("ModuleNotSavedCaption"), MessageBoxButton.YesNoCancel, MessageBoxImage.Exclamation, MessageBoxResult.Cancel, opt);
                switch (result)
                {
                    case MessageBoxResult.Cancel:
                        break;
                    case MessageBoxResult.No:
                            return true;

                    case MessageBoxResult.Yes:
                        Model.Save();
                        if (StatusStrip.Status == "green")
                        {
                            return true;
                        }
                        break;
                    default:
                        break;
                }
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool YellowStatusWarning(string MessageText, string CaptionText)
        {
            MessageBoxOptions opt = MessageBoxOptions.None;
            if (this.FlowDirection == FlowDirection.RightToLeft) opt = MessageBoxOptions.RtlReading;
            MessageBoxResult result = MessageBox.Show(MessageText, CaptionText, MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.Cancel, opt);

            switch (result)
            {
                case MessageBoxResult.Cancel:
                    break;

                case MessageBoxResult.No:
                    return false;
                    
                case MessageBoxResult.Yes:
                    return true;
                    
                default:
                    break;
            }
            return false;
        }

        private void ResourceLanguage_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (ResourceLanguage.SelectedValue == null)
                return;

            BusinessEntities.XAppLanguage appLanguage = ResourceLanguage.SelectedItem as BusinessEntities.XAppLanguage;
            Model.FilterAppResource(appLanguage);
        }

        #endregion

        private void FieldTrackingList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (FieldTrackingList.SelectedItem != null)
            {
                BusinessEntities.XConfigLogFields selectedItem = (BusinessEntities.XConfigLogFields)FieldTrackingList.SelectedItem;
                Model.EditFieldTracking(selectedItem);
            }
        }

        private void DialogName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (DialogName.SelectedValue == null)
                return;

            BusinessEntities.XDialogName dialogName = DialogName.SelectedItem as BusinessEntities.XDialogName;
            Model.FilterConfigUIControls(dialogName);
        }

        private void ConfigUIControlsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (ConfigUIControlsList.SelectedItem != null)
            {
                BusinessEntities.XConfigUIControls selectedItem = (BusinessEntities.XConfigUIControls)ConfigUIControlsList.SelectedItem;
                Model.EditConfigUIControls(selectedItem);
            }
        }

        private void WorkflowUIControlsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (WorkflowUIControlsList.SelectedItem != null)
            {
                BusinessEntities.XConfigWorkflowUIControls selectedItem = (BusinessEntities.XConfigWorkflowUIControls)WorkflowUIControlsList.SelectedItem;
                Model.EditConfigWorkFlowUIControls(selectedItem);
            }
        }

        private void WorkflowDialogName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (WorkflowDialogName.SelectedValue == null)
                return;

            BusinessEntities.XDialogName dialogName = WorkflowDialogName.SelectedItem as BusinessEntities.XDialogName;
            Model.FilterConfigWorkFlowUIControls(dialogName);
        }

        private void FieldValidationsList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (FieldValidationsList.SelectedValue == null)
                return;

            BusinessEntities.XFieldValidation fieldValidation = FieldValidationsList.SelectedItem as BusinessEntities.XFieldValidation;
            Model.EditFieldValidation(fieldValidation);
        }

        private void MenuMainMenuItemsList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (MenuMainMenuItemsList.SelectedValue == null)
                return;

            BusinessEntities.MenuMainMenu mainMenu = MenuMainMenuItemsList.SelectedItem as BusinessEntities.MenuMainMenu;
            Model.FillSubMenu(mainMenu);
        }

        private void WorkflowEntityName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (WorkflowEntityName.SelectedValue == null)
                return;

            Model.FillEnterpriseWorkflows(WorkflowEntityName.SelectedValue.ToString());
        }

        private void WorkflowName_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (WorkflowName.SelectedValue == null)
                return;

            Model.FilterEnterpriseWorkflowStatuses(WorkflowName.SelectedValue.ToString());
        }

        ListBox m_DragSource;

        private void MenuSubMenuItemsList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            m_DragSource = sender as ListBox;
            MenuSubMenu data = GetDataFromListBox(m_DragSource, e.GetPosition(m_DragSource)) as MenuSubMenu;

            if (data != null)
            {
                DragDrop.DoDragDrop(m_DragSource, data, DragDropEffects.Move);
            }
        }

        private void MenuMainMenuItemsList_Drop(object sender, DragEventArgs e)
        {
            ListBox destination = (ListBox)sender;            
            MenuMainMenu mainMenuItem = GetDataFromListBox(destination, e.GetPosition(destination)) as MenuMainMenu;

            if (mainMenuItem == null)
                return;
            
            destination.SelectedItem = mainMenuItem;

            MenuSubMenu subMenuItem = e.Data.GetData(typeof(MenuSubMenu)) as MenuSubMenu;

            if (subMenuItem == null)
                return;

            Model.MoveSubMenuToNewMenu(mainMenuItem, subMenuItem);
        }

        private object GetDataFromListBox(ListBox source, Point point)
        {
            UIElement element = source.InputHitTest(point) as UIElement;
            
            if (element != null)
            {
                object data = DependencyProperty.UnsetValue;
                while (data == DependencyProperty.UnsetValue)
                {
                    data = source.ItemContainerGenerator.ItemFromContainer(element);

                    if (data == DependencyProperty.UnsetValue)
                    {
                        element = VisualTreeHelper.GetParent(element) as UIElement;
                    }

                    if (element == source)
                    {
                        return null;
                    }
                }

                if (data != DependencyProperty.UnsetValue)
                {
                    return data;
                }
            }

            return null;
        }
    }
}

